/*
 * GameManager.java
 */
package othello.logic;

import othello.GUIC;
import othello.logic.player.Human;
import othello.logic.player.Player;

/**
 * Class GameManager
 * Creates a new game instance.
 * Asks the players for their next moves, and applies it to the GameGrid.
 * Also keeps track of who won and calls the correct dialog.
 */

public class GameManager {

    final int BLACK = 1;
    final int WHITE = 2;
    final int WIDTH = 8;
    final int HEIGHT = 8;
    Player p1;
    Player p2;
    GameGrid gameGrid;
    GUIC guic;
    MoveQueue moveQueue;
    
    public GameManager(GUIC guic) {
        p1 = guic.getPlayer1();
        p2 = guic.getPlayer2();

        this.guic = guic;

        gameGrid = new GameGrid();
        moveQueue = new MoveQueue();
    }
    
    public void newRound() {
        boolean blackState, whiteState;
        Coordinates nextMove;
        
        gameGrid.clearGrid();
        guic.setNewMoveQueue(moveQueue);
        guic.setNewGrid(gameGrid);
        
        if (p1 instanceof Human)
            p1.setMoveQueue(moveQueue);
        
        if (p2 instanceof Human)
            p2.setMoveQueue(moveQueue);

        while (true) {
            if (blackState = validMoves(BLACK)) {
                while (true) {
                    nextMove = p1.getNextMove();
                    if (gameGrid.makeMove(BLACK, nextMove)) {
                        guic.repaintBoard();
                        break;
                    }
                }
            }
            if (whiteState = validMoves(WHITE)) {
                while (true) {
                    nextMove = p2.getNextMove();
                    if (gameGrid.makeMove(WHITE, nextMove)) {
                        guic.repaintBoard();
                        break;
                    }
                }
            }
            if (!whiteState && !blackState) {
                break;
            }
        }
        switch (gameGrid.countWinner()) {
            case -1:
                guic.showDrawDialog();
                break;
            case BLACK:
                guic.showWinnerDialog(p1.getPlayerName());
                break;
            case WHITE:
                guic.showWinnerDialog(p2.getPlayerName());
                break;
        }
    }

    private boolean validMoves(int color) {
        for (int i = 0; i < WIDTH; i++) {
            for (int j = 0; j < HEIGHT; j++) {
                if (gameGrid.validMove(color, new Coordinates(i, j))) {
                    return true;
                }
            }
        }
        return false;
    }

    public void setNewPlayers(GUIC guic) {
        p1 = guic.getPlayer1();
        p2 = guic.getPlayer2();
    }
}
